#include "imagelabel.h"
#include <QDebug>
#include <QDropEvent>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QMessageBox>
#include <QPainter>
#include <QScreen>
#include <QGuiApplication>
ImageLabel::ImageLabel(QWidget *parent) : QLabel(parent)
{
    this->setAcceptDrops(true); //必须设置，不然无法接收拖放事件
}

ImageLabel::~ImageLabel()
{

}

void ImageLabel::dragEnterEvent(QDragEnterEvent *event)
{
    qDebug()<<"dragEnterEvent";
    if(event->mimeData()->hasUrls())
    {
        event->acceptProposedAction(); //事件数据中存在路径，方向事件, 不接收的话dropEvent事件不会触发
        qDebug()<<"dragEnterEvent"<<event->mimeData()->urls();
    }
    else
    {
        event->ignore();//表示不要这类事件，继续往其他部件传递
    }
}

void ImageLabel::dragMoveEvent(QDragMoveEvent *event)
{
qDebug()<<"dragMoveEvent";
}

void ImageLabel::dropEvent(QDropEvent *event)
{
    qDebug()<<"dropEvent";
    const QMimeData *mimeData = event->mimeData();
    if(mimeData->hasUrls())
    {
        QList<QUrl> urls = mimeData->urls();
        QString fileName = urls.at(0).toLocalFile();
        int index=fileName.lastIndexOf(".");
        QString Suffix=fileName.mid(index,-1);
        qDebug()<<"PATH"<<fileName<<Suffix;
        if(Suffix.indexOf("png")!=-1
                ||Suffix.indexOf("jpg")!=-1
                ||Suffix.indexOf("JPG")!=-1
                ||Suffix.indexOf("jpeg")!=-1
                ||Suffix.indexOf("bmp")!=-1
                )
        {
            qDebug()<<"IsOk";
            m_DataList.append(fileName);
            m_data=qvariant_cast<QImage>(mimeData->imageData());
            QImage img;
            if(!(img.load(fileName))) //加载图像
            {
                QMessageBox::information(this, tr("打开图像失败"),tr("打开图像失败!"));
                return;
            }
            int width=img.width();
            int height=img.height();

            int lenght;
            if(width<height){
                lenght=width;
            }else{
                lenght=height;
            }

            this->setPixmap(QPixmap::fromImage(img.scaled(this->size())));
        }
        else
        {
            qDebug()<<"IsNo";
            QMessageBox::critical(NULL,QString("警告!"),QString("无法完成请求，因为它不是所指类型文档！"),QString("确定"));
        }
    }

}

void ImageLabel::dragLeaveEvent(QDragLeaveEvent *event)
{
qDebug()<<"dragLeaveEvent";
}

//void ImageLabel::paintEvent(QPaintEvent *event)
//{
//    if(m_DataList.count()>0)
//    {
//        QPainter painter(this);
////        QImage image(m_DataList.at(0));
////        painter.drawImage(this->rect(),image);

//        QPixmap map(m_DataList.at(0));
//        painter.drawPixmap(this->rect(),map);
//        qDebug()<<"paintEvent";
//    }
//      //QLabel::paintEvent(event);
//}
